<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Weixin_interface extends CI_Controller {

    function __construct (){
	    parent::__construct();
    }

	public function index()
	{
		$this->load->library('WeChatCallBack');

		if($this->checkSignature()) {
			if($_GET["echostr"]) {
				echo $_GET["echostr"];
				exit(0);
			}
		} else {
			//恶意请求：获取来来源ip，并写日志
			exit(0);
			
		}
		
		$postStr = file_get_contents ( "php://input" );
		
		if (empty ( $postStr )) {
			exit(0);
		}
		
		$postObj = simplexml_load_string ( $postStr, 'SimpleXMLElement', LIBXML_NOCDATA );
		
		if(NULL == $postObj) {
			exit(0);
		}
		
		$ret = $this->wechatcallback->init($postObj);
        $this->wechatcallback->process();
	}
	
	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];

		$token = WEIXIN_TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}
